#include "BondDealMatrixSettingDlg.h"
#include <QHBoxLayout>
#include <QPushButton>
#include <qbfixedincome/StringResource.h>
#include <QStylePainter>
#include <QSettings>
#include <core/FileSys.h>
#include <widgets/SCheckEx.h>
#include <core/ImageMgr.h>
#include <QScrollArea>
#include <bondlib/BondDeal/BondDealTermRange.h>
#include <core/Utility.h>
#include <widgets/STips.h>

using namespace qb;

DoubleSpinBox::DoubleSpinBox(QWidget* p,bool bLeftSpinBox)
	: QDoubleSpinBox(p),m_bLeftSpinBox(bLeftSpinBox)
{

}

void DoubleSpinBox::wheelEvent(QWheelEvent* event)
{
	return;
}

//单独封装期限label
TermSettingLabel::TermSettingLabel(QWidget* p, QString term, QString leftUnit, QString rightUnit,bool haveDoubleSpinBox,QString leftNum, QString rightNum)
	: QLabel(p),
	m_term(term),
	m_leftDateUnit(leftUnit),
	m_rightDateUnit(rightUnit),
	m_leftNum(leftNum),
	m_rightNum(rightNum),
	m_haveDoubleSpinBox(haveDoubleSpinBox)
{
	setFixedSize(374, 32);

	if (m_haveDoubleSpinBox)
	{
		auto hLayout = new QHBoxLayout(this);
		hLayout->setContentsMargins(0, 0, 0, 0);
		hLayout->addSpacing(72);

		QString spinBoxStyleSheet = QString(
			"QDoubleSpinBox				{border:1px solid #%1;background-color:#%2;color:#%3;}"
			"QDoubleSpinBox:hover		{background-color:#%4;}"
		)
			.arg(NAME_COLOR("BorderNormal").rgb(), 0, 16)
			.arg(NAME_COLOR("BackNormal").rgb(), 0, 16)
			.arg(NAME_COLOR("TextNormal").rgb(), 0, 16)
			.arg(NAME_COLOR("Hover").rgb(), 0, 16);

		m_doubleSpinBoxLeft = new DoubleSpinBox(this,true);
		m_doubleSpinBoxLeft->setStyleSheet(spinBoxStyleSheet);
		m_doubleSpinBoxLeft->setSingleStep(0.1);
		m_doubleSpinBoxLeft->setRange(0, 100);
		m_doubleSpinBoxLeft->setFixedSize(94, 24);
		m_doubleSpinBoxLeft->setDecimals(1);
		hLayout->addWidget(m_doubleSpinBoxLeft);

		hLayout->addSpacing(32);

		m_doubleSpinBoxRight = new DoubleSpinBox(this,false);
		m_doubleSpinBoxRight->setStyleSheet(spinBoxStyleSheet);
		m_doubleSpinBoxRight->setSingleStep(0.1);
		m_doubleSpinBoxRight->setRange(0, 100);
		m_doubleSpinBoxRight->setFixedSize(94, 24);
		m_doubleSpinBoxRight->setDecimals(1);
		hLayout->addWidget(m_doubleSpinBoxRight);
		hLayout->addStretch(-1);
	}
}

void TermSettingLabel::setSelectState(Qt::CheckState v, bool notify)
{
	m_selectState = v;
	update();
	if (notify)
		emit stateChanged(m_index);
}

void TermSettingLabel::setIndex(int index)
{
	m_index = index;
	if (m_haveDoubleSpinBox)
	{
		m_doubleSpinBoxLeft->m_index = index;
		m_doubleSpinBoxRight->m_index = index;
	}
}

void TermSettingLabel::setSpinBoxText(const char* leftValue,const char* rightValue)
{
	if (!m_haveDoubleSpinBox && !m_doubleSpinBoxLeft && !m_doubleSpinBoxRight) return;
	QString strleft(leftValue);
	QString stright(rightValue);
	if (!strleft.isEmpty() && !stright.isEmpty())
	{
		strleft = strleft.left(strleft.length() - 1);
		stright = stright.left(stright.length() - 1);
	}
	double lvalue = strleft.toDouble();
	m_doubleSpinBoxLeft->setValue(lvalue);
	double rvalue = stright.toDouble();
	m_doubleSpinBoxRight->setValue(rvalue);
}

QString TermSettingLabel::getSpinBoxText(bool bLeftSpinBox) const
{
	if (!m_haveDoubleSpinBox && !m_doubleSpinBoxLeft && !m_doubleSpinBoxRight) return "";

	QString strValue;
	if (bLeftSpinBox)
		strValue = QString::number(m_doubleSpinBoxLeft->value());
	else
		strValue = QString::number(m_doubleSpinBoxRight->value());
	return strValue;
}

void TermSettingLabel::paintEvent(QPaintEvent* event)
{
	QLabel::paintEvent(event);

	QStylePainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);

	QRect r = rect();
	QFontMetrics fm(font());

	//绘制背景
	QColor bkColor = StyleMgr::instance().color("StaticTextBK");
	painter.setBrush(bkColor);
	painter.setPen(bkColor);
	painter.drawRoundedRect(rect(), StyleMgr::instance().size("RoundCorner"), StyleMgr::instance().size("RoundCorner"));

	QString imgName = m_selectState == Qt::Checked ? "widgets_check_selected" : "widgets_check";

	WidgetStatus status = isEnabled() ? (m_hover ? WidgetStatus::kHover : WidgetStatus::kNormal) : WidgetStatus::kDisabled;
	SImage* img = ImgMgr::instance().image(imgName, status, devicePixelRatioF());
	QRect indicatorRect = rect();
	if (img)
	{
		int width = img->width();
		int height = img->height();
		int y = (rect().height() - height) / 2;
		indicatorRect.setRect(StyleMgr::instance().size("CtrlSpacing"), y, width, height);
		m_indicatorRect = indicatorRect;
		painter.drawImage(indicatorRect, *img);
	}

	painter.setPen(NAME_COLOR("SupportingWord"));

	if (!m_term.isEmpty())
	{
		int termX = r.x() + 68;
		int termWidth = fm.horizontalAdvance(m_term);

		QRect termRect;
		termRect.setRect(termX - termWidth, r.y(), termWidth + 10, r.height());
		painter.drawText(termRect, m_term, QTextOption(Qt::AlignVCenter));
	}

	if (!m_leftDateUnit.isEmpty())
	{
		int leftDateUnitX = r.x() + 173;
		int leftDateUnitWidth = fm.horizontalAdvance(m_leftDateUnit);

		QRect leftDateUnitRect;
		leftDateUnitRect.setRect(leftDateUnitX, r.y(), leftDateUnitWidth, r.height());
		painter.drawText(leftDateUnitRect, m_leftDateUnit, QTextOption(Qt::AlignVCenter));

		// -
		int x = leftDateUnitX + leftDateUnitWidth + 6;
		int width = fm.horizontalAdvance("—");
		QRect rect;
		rect.setRect(x, r.y(), width, r.height());
		painter.drawText(rect, "-", QTextOption(Qt::AlignVCenter));
	}

	if (!m_rightDateUnit.isEmpty())
	{
		int rightDateUnitX = r.x() + 308;
		int rightDateUnitWidth = fm.horizontalAdvance(m_rightDateUnit);

		QRect rightDateUnitRect;
		rightDateUnitRect.setRect(rightDateUnitX, r.y(), rightDateUnitWidth, r.height());
		painter.drawText(rightDateUnitRect, m_rightDateUnit, QTextOption(Qt::AlignVCenter));
	}

	if (!m_haveDoubleSpinBox && !m_leftNum.isEmpty() && !m_rightNum.isEmpty()) // 超长termLabel
	{
		int leftNumberX = r.x() + 105;
		int leftNumberWidth = fm.horizontalAdvance(m_leftNum);

		QRect leftNumRect;
		leftNumRect.setRect(leftNumberX, r.y(), leftNumberWidth, r.height());
		painter.drawText(leftNumRect, m_leftNum, QTextOption(Qt::AlignVCenter));

		int rightNumberX = r.x() + 236;
		int rightNumberWidth = fm.horizontalAdvance(m_rightNum);

		QRect rightNumRect;
		rightNumRect.setRect(rightNumberX, r.y(), rightNumberWidth, r.height());
		painter.drawText(rightNumRect, m_rightNum, QTextOption(Qt::AlignVCenter));
	}
}

void TermSettingLabel::mousePressEvent(QMouseEvent* event)
{
	if (m_indicatorRect.contains(event->pos()))
	{
		if (m_selectState == Qt::Unchecked)
			m_selectState = Qt::Checked;
		else
			m_selectState = Qt::Unchecked;

		update();
		emit stateChanged(m_index);
	}
}

void TermSettingLabel::enterEvent(QEvent* event)
{
	const QMouseEvent* ev = static_cast<QMouseEvent*>(event);
	if (m_indicatorRect.contains(ev->pos()))
	{
		m_hover = true;
		update();
	}
}

void TermSettingLabel::leaveEvent(QEvent* event)
{
	const QMouseEvent* ev = static_cast<QMouseEvent*>(event);
	if (m_indicatorRect.contains(ev->pos()))
	{
		m_hover = false;
		update();
	}
}

TermSettingArea::TermSettingArea(QWidget* p, eBondType type)
	: QWidget(p), m_type(type)
{
	auto vLayout = new QVBoxLayout(this);
	vLayout->setContentsMargins(0, 0, 0, 0);

	int rangeTemp;

	switch (m_type)
	{
	case BOND_GOV:
		rangeTemp = 11;
		for (int i = 0; i <= rangeTemp - 1; i++)
		{
			if (i == 0)
			{
				termLabel = new TermSettingLabel(this, NewStringTable::strFixedScrMatrixIntCol(1), "M", "Y",true);
			}
			else if (i == 10)
			{
				termLabel = new TermSettingLabel(this, NewStringTable::strFixedScrMatrixIntCol(11), "Y", "Y", false,"10","50");
			}
			else
			{
				termLabel = new TermSettingLabel(this, NewStringTable::strFixedScrMatrixIntCol(i + 1), "Y", "Y",true);
			}
			termLabel->setIndex(i);
			vLayout->addWidget(termLabel);
			vLayout->addSpacing(4);
			m_vAreaLabels.push_back(termLabel);
		}
		break;
	case BOND_CREDIT:
		rangeTemp = 10;
		for (int i = 0; i <= rangeTemp - 1; i++)
		{
			if (i <= 2)
			{
				termLabel = new TermSettingLabel(this, NewStringTable::strFixedScrMatrixCrdCol(i + 1), "M", "M",true);
			}
			else if (i == 3)
			{
				termLabel = new TermSettingLabel(this, NewStringTable::strFixedScrMatrixCrdCol(i + 1), "M", "Y",true);
			}
			else
			{
				termLabel = new TermSettingLabel(this, NewStringTable::strFixedScrMatrixCrdCol(i + 1), "Y", "Y",true);
			}
			termLabel->setIndex(i);
			vLayout->addWidget(termLabel);
			vLayout->addSpacing(4);
			m_vAreaLabels.push_back(termLabel);
		}
		break;
	case BOND_NCDTrade:
		rangeTemp = 7;
		for (int i = 0; i <= rangeTemp - 1; i++)
		{
			termLabel = new TermSettingLabel(this, NewStringTable::strFixedScrMatrixNCDTradeCol(i + 1), "M", "M",true);
			termLabel->setIndex(i);
			vLayout->addWidget(termLabel);
			vLayout->addSpacing(4);
			m_vAreaLabels.push_back(termLabel);
		}
		break;
	default:
		break;
	}
}

//期限设置
MatrixTermSetting::MatrixTermSetting(QWidget* p, int bondType, xQBBondDealTermRgReq* req)
	:QWidget(p) ,m_req(req)
{
	auto vLayout = new QVBoxLayout(this);
	vLayout->setContentsMargins(0, 13, 0, 0);

	m_tabType = new STabCtrl(this);
	m_tabType->addTab(NewStringTable::strBDMatrixerm(1));
	m_tabType->addTab(NewStringTable::strBDMatrixerm(2));
	m_tabType->addTab(NewStringTable::strBDMatrixerm(16));
	m_tabType->setFixedSize(384, 22);
	vLayout->addWidget(m_tabType);
	vLayout->addSpacing(14);

	//利率债
	m_bondGovLabelArea = new TermSettingArea(this,BOND_GOV);
	m_bondGovLabelArea->setMaximumHeight(410); 
	m_bondGovScrollArea = new QScrollArea(this);
	m_bondGovScrollArea->setStyleSheet("background-color:transparent;");
	m_bondGovScrollArea->setWidgetResizable(true);
	m_bondGovScrollArea->setFrameShape(QFrame::NoFrame);
	m_bondGovScrollArea->setWidget(m_bondGovLabelArea);
	vLayout->addWidget(m_bondGovScrollArea);

	//信用债
	m_bondCreditLabelArea = new TermSettingArea(this, BOND_CREDIT);
	m_bondCreditLabelArea->setMaximumHeight(373); 
	m_bondCreditScrollArea = new QScrollArea(this);
	m_bondCreditScrollArea->setStyleSheet("background-color:transparent;");
	m_bondCreditScrollArea->setWidgetResizable(true);
	m_bondCreditScrollArea->setFrameShape(QFrame::NoFrame);
	m_bondCreditScrollArea->setWidget(m_bondCreditLabelArea);
	vLayout->addWidget(m_bondCreditScrollArea);
	m_bondCreditLabelArea->hide();
	m_bondCreditScrollArea->hide();

	//NCD二级成交
	m_bondNCDLabelArea = new TermSettingArea(this, BOND_NCDTrade);
	m_bondNCDLabelArea->setMaximumHeight(258);
	m_bondNCDScrollArea = new QScrollArea(this);
	m_bondNCDScrollArea->setStyleSheet("background-color:transparent;");
	m_bondNCDScrollArea->setWidgetResizable(true);
	m_bondNCDScrollArea->setFrameShape(QFrame::NoFrame);
	m_bondNCDScrollArea->setWidget(m_bondNCDLabelArea);
	vLayout->addWidget(m_bondNCDScrollArea);
	m_bondNCDLabelArea->hide();
	m_bondNCDScrollArea->hide();

	vLayout->addStretch(-1);

	connect(m_tabType, &STabCtrl::tabSelected, this, &MatrixTermSetting::onChangeBondTab);
	setTabType(bondType);
}

void MatrixTermSetting::setTabType(int nType)
{
	m_tabType->selectTab(nType == 3 ? nType - 1 :nType);
	m_tabCurrent = nType;
	initData();
	initRangeInput();
	onChangeBondTab(nType);
}

void MatrixTermSetting::saveConfig(bool binitData)
{
	QSettings settings(FileSys::instance()->writeableAppCfgDir() + "/gszhConfig.ini", QSettings::IniFormat);

	if (m_tabCurrent == BOND_GOV || binitData)
	{
		settings.beginGroup("fiGovRange");
		settings.setValue("range1", m_IntData[0]);
		settings.setValue("range2", m_IntData[1]);
		settings.setValue("range3", m_IntData[2]);
		settings.setValue("range4", m_IntData[3]);
		settings.setValue("range5", m_IntData[4]);
		settings.setValue("range6", m_IntData[5]);
		settings.setValue("range7", m_IntData[6]);
		settings.setValue("range8", m_IntData[7]);
		settings.setValue("range9", m_IntData[8]);
		settings.setValue("range10", m_IntData[9]);
		settings.setValue("range11", m_IntData[10]);
		settings.endGroup();
	}
	if (m_tabCurrent == BOND_CREDIT || binitData)
	{
		settings.beginGroup("fiGreditRange");
		settings.setValue("range1", m_CretData[0]);
		settings.setValue("range2", m_CretData[1]);
		settings.setValue("range3", m_CretData[2]);
		settings.setValue("range4", m_CretData[3]);
		settings.setValue("range5", m_CretData[4]);
		settings.setValue("range6", m_CretData[5]);
		settings.setValue("range7", m_CretData[6]);
		settings.setValue("range8", m_CretData[7]);
		settings.setValue("range9", m_CretData[8]);
		settings.setValue("range10", m_CretData[9]);
		settings.endGroup();
	}
	if (m_tabCurrent == BOND_NCDTrade || binitData)
	{
		settings.beginGroup("fiNCDRange");
		settings.setValue("range1", m_NCDData[0]);
		settings.setValue("range2", m_NCDData[1]);
		settings.setValue("range3", m_NCDData[2]);
		settings.setValue("range4", m_NCDData[3]);
		settings.setValue("range5", m_NCDData[4]);
		settings.setValue("range6", m_NCDData[5]);
		settings.setValue("range7", m_NCDData[6]);
		settings.endGroup();
	}
}

void MatrixTermSetting::saveRangeInfo()
{
	//保存之前的数据存储
	for (auto& itRate : m_req->m_matrixTerm) {
		if (itRate.m_nRate != m_tabCurrent) continue; //仅仅保存的是当前tab的
		int rank = 0;
		for (auto& itRange : itRate.m_listTerm) {
			FIELDCOPY(itRange.m_rangeLeft,  getRangeValue(rank, (itRange.m_rangeLeft),true).toStdString().c_str());
			FIELDCOPY(itRange.m_rangeRight, getRangeValue(rank, (itRange.m_rangeRight),false).toStdString().c_str());
			++rank;
		}
	}
}

void MatrixTermSetting::initData()
{
	std::vector<UINT> vRangeData;
	int RangeNum = getConfig(vRangeData, m_tabCurrent);
	if (RangeNum == 0)
	{
		for (int i = 0; i < 11; i++)
		{
			m_IntData[i] = 1;
			if (i < 10)	 m_CretData[i] = 1;
			if (i < 7)	 m_NCDData[i] = 1;
		}

		m_IntData[6] = 0;
		m_IntData[7] = 0;
		m_IntData[8] = 0;
		m_IntData[9] = 0;
		m_CretData[6] = 0;
		m_CretData[8] = 0;
		m_CretData[9] = 0;
		m_NCDData[0] = 0;
		saveConfig(true);
	}
}

int MatrixTermSetting::getConfig(std::vector<UINT>& vRangeData, const int& rangeType) const
{
	int rangeNum = 0;

	QSettings settings(FileSys::instance()->writeableAppCfgDir() + "/gszhConfig.ini", QSettings::IniFormat);

	if (rangeType == BOND_GOV)
	{
		settings.beginGroup("fiGovRange");
		vRangeData.push_back(settings.value("range1").toInt());
		vRangeData.push_back(settings.value("range2").toInt());
		vRangeData.push_back(settings.value("range3").toInt());
		vRangeData.push_back(settings.value("range4").toInt());
		vRangeData.push_back(settings.value("range5").toInt());
		vRangeData.push_back(settings.value("range6").toInt());
		vRangeData.push_back(settings.value("range7").toInt());
		vRangeData.push_back(settings.value("range8").toInt());
		vRangeData.push_back(settings.value("range9").toInt());
		vRangeData.push_back(settings.value("range10").toInt());
		vRangeData.push_back(settings.value("range11").toInt());
		settings.endGroup();
	}
	if (rangeType == BOND_CREDIT)
	{
		settings.beginGroup("fiGreditRange");
		vRangeData.push_back(settings.value("range1").toInt());
		vRangeData.push_back(settings.value("range2").toInt());
		vRangeData.push_back(settings.value("range3").toInt());
		vRangeData.push_back(settings.value("range4").toInt());
		vRangeData.push_back(settings.value("range5").toInt());
		vRangeData.push_back(settings.value("range6").toInt());
		vRangeData.push_back(settings.value("range7").toInt());
		vRangeData.push_back(settings.value("range8").toInt());
		vRangeData.push_back(settings.value("range9").toInt());
		vRangeData.push_back(settings.value("range10").toInt());
		settings.endGroup();
	}
	if (rangeType == BOND_NCDTrade)
	{
		settings.beginGroup("fiNCDRange");
		vRangeData.push_back(settings.value("range1").toInt());
		vRangeData.push_back(settings.value("range2").toInt());
		vRangeData.push_back(settings.value("range3").toInt());
		vRangeData.push_back(settings.value("range4").toInt());
		vRangeData.push_back(settings.value("range5").toInt());
		vRangeData.push_back(settings.value("range6").toInt());
		vRangeData.push_back(settings.value("range7").toInt());
		settings.endGroup();
	}

	for (auto data : vRangeData)
	{
		if (data == 1)
			rangeNum++;
	}

	return rangeNum;
}

QString MatrixTermSetting::getRangeValue(int rank, QString strBefore, bool bLeftSpinBox) const
{//bLeftSpinBox false时取得是右侧SpinBox值
	QString strText;
	if (m_tabCurrent == BOND_GOV)
	{
		if (rank == 10) 
			return strText = bLeftSpinBox == true ? "10Y" : "50Y";
		strText = m_bondGovLabelArea->m_vAreaLabels[rank]->getSpinBoxText(bLeftSpinBox);
	}
	else if (m_tabCurrent == BOND_CREDIT)
	{
		strText = m_bondCreditLabelArea->m_vAreaLabels[rank]->getSpinBoxText(bLeftSpinBox);
	}
	else if (m_tabCurrent == BOND_NCDTrade)
	{
		strText = m_bondNCDLabelArea->m_vAreaLabels[rank]->getSpinBoxText(bLeftSpinBox);
	}

	if (!strText.isEmpty() && strText.right(1) == ".") {
		strText = strText.left(strText.length() - 1);
	}
	int strNum = strText.indexOf(".");
	if (strNum != -1 && (strNum + 1) < strText.length()) { 
		strText = strText.left(strNum + 2);
	}
	if (strText.isEmpty()) {
		strText = "0";
	}
	strText += strBefore.right(1);
	return strText;
}

//根据config修改Checked值(或为默认)
void MatrixTermSetting::changeTermRangeText()
{
	vector<UINT> vRangeData;
	int rangeNum = 0;
	std::vector<bool> interstCheck = { true,true,true,true,true,true,false,false,false,false,true };
	std::vector<bool> creditCheck  = { true,true,true,true,true,true,false,true,true,true };
	std::vector<bool> ncdCheck = { true,true,false,true,true,true,true };
	rangeNum = getConfig(vRangeData, m_tabCurrent);

	for (int i = 0; i <= ID_CHK_LONGTERM - ID_CHK_1Y; i++)
	{
		if (m_tabCurrent == eBondType::BOND_GOV)
		{
			bool bSelected = rangeNum > 0 ? vRangeData[i] : interstCheck[i];
			m_bondGovLabelArea->m_vAreaLabels[i]->setSelectState(bSelected == true ? Qt::Checked : Qt::Unchecked, false);
		}
		else if (m_tabCurrent == eBondType::BOND_CREDIT)
		{
			if (i < 10)
			{
				bool bSelected = rangeNum > 0 ? vRangeData[i] : creditCheck[i];
				m_bondCreditLabelArea->m_vAreaLabels[i]->setSelectState(bSelected == true ? Qt::Checked : Qt::Unchecked, false);
			}
		}
		else if (m_tabCurrent == eBondType::BOND_NCDTrade)
		{
			if (i < 7)
			{
				bool bSelected = rangeNum > 0 ? vRangeData[i] : ncdCheck[i];
				m_bondNCDLabelArea->m_vAreaLabels[i]->setSelectState(bSelected == true ? Qt::Checked : Qt::Unchecked, false);
			}
		}
	}
}

void MatrixTermSetting::resetRangePairStatus(int rank)
{
	bool findRange = false;
	int rangeTemp;
	if (m_tabCurrent == BOND_GOV || m_tabCurrent == BOND_CREDIT)
	{
		rangeTemp = 10;
	}
	else if (m_tabCurrent == BOND_NCDPrimary)
	{
		rangeTemp = 5;
	}
	else if (m_tabCurrent == BOND_NCDTrade)
	{
		rangeTemp = 7;
	}

	if (rank > rangeTemp || rank < 0)return;

	int dateLeft = 0 ,dateRight = 0;
	int nextdateLeft = 0 ,nextdateRight = 0;
	int dateRightBefore = 0;
	
	CBondDealTermRange& range = CBondDealTermRange::instance();

	for (auto& itRate : m_req->m_matrixTerm) {
		if (itRate.m_nRate != m_tabCurrent) continue;
		int tempRank = 0;
		for (auto& itRange : itRate.m_listTerm) {
			if (findRange == true)
			{
				//找到则取下一级的数据，用于区间判断
				FIELDCOPY(itRange.m_rangeLeft, getRangeValue(tempRank, (itRange.m_rangeLeft), true).toStdString().c_str());
				FIELDCOPY(itRange.m_rangeRight, getRangeValue(tempRank, (itRange.m_rangeRight), false).toStdString().c_str());
				nextdateLeft = range.CalcDays(itRange.m_rangeLeft);
				nextdateRight = range.CalcDays(itRange.m_rangeRight);
				break;
			}

			if (rank == tempRank) {
				FIELDCOPY(itRange.m_rangeLeft, getRangeValue(rank, (itRange.m_rangeLeft), true).toStdString().c_str());
				FIELDCOPY(itRange.m_rangeRight, getRangeValue(rank, (itRange.m_rangeRight),false).toStdString().c_str());
				dateLeft = range.CalcDays(itRange.m_rangeLeft);
				dateRight = range.CalcDays(itRange.m_rangeRight);
				findRange = true;
			}

			//保存上次信息用于判断
			if (findRange == false)
			{
				FIELDCOPY(itRange.m_rangeRight, getRangeValue(tempRank, (itRange.m_rangeRight), false).toStdString().c_str());
				dateRightBefore = range.CalcDays(itRange.m_rangeRight);
			}

			tempRank += 1;
			if (tempRank == rangeTemp)
			{
				break;
			}
		}
	}
	
	auto label = getTabTermSettingArea(m_tabCurrent)->m_vAreaLabels[rank];
	if (label == nullptr) return;
	auto labelLeftSpinBox = label->getLeftSpinBox();
	auto labelRightSpinBox = label->getRightSpinBox();

	//本级别左右侧比较
	bool bErrorStatus = (dateLeft < dateRight) ? false : true;
	if (labelLeftSpinBox->getStatusError() != bErrorStatus && labelRightSpinBox->getStatusError() != bErrorStatus)
	{
		labelLeftSpinBox->setStatusError(bErrorStatus);
		labelRightSpinBox->setStatusError(bErrorStatus);
		m_errType = 0;
		return;
	}


	//本级别右侧和下一级左侧比较
	if (rank + 1 != rangeTemp) {
		bErrorStatus = (dateRight <= nextdateLeft) ? false : true;

		auto nextLabel = getTabTermSettingArea(m_tabCurrent)->m_vAreaLabels[rank + 1];
		if (nextLabel == nullptr) return;
		auto nextLabelLeftSpinBox = nextLabel->getLeftSpinBox();
		//本级勾选  
		if ((labelRightSpinBox->getStatusError() != bErrorStatus) && (nextLabelLeftSpinBox->getStatusError() != bErrorStatus) 
		&& (noChooseErrorCheck(m_tabCurrent,rank) == false))
		{
			labelRightSpinBox->setStatusError(bErrorStatus);
			nextLabelLeftSpinBox->setStatusError(bErrorStatus);
			m_errType = 1;
			return;
		}
		//本级不勾选
		if ((labelRightSpinBox->getStatusError() == 1) && (nextLabelLeftSpinBox->getStatusError() == 1)
			&& (noChooseErrorCheck(m_tabCurrent, rank) == true))
		{
			labelRightSpinBox->setStatusError(0);
			nextLabelLeftSpinBox->setStatusError(0);
			m_errType = 1;
			return;
		}
	}

	//本级别左侧和上一级别右侧比较
	bErrorStatus = (dateLeft >= dateRightBefore) ? false : true;
	if (rank > 0)
	{
		auto lastLabel = getTabTermSettingArea(m_tabCurrent)->m_vAreaLabels[rank - 1];
		if (lastLabel == nullptr) return;
		auto lastLabelRightSpinBox = lastLabel->getRightSpinBox();

		if ((labelLeftSpinBox->getStatusError() != bErrorStatus) && (lastLabelRightSpinBox->getStatusError() != bErrorStatus)
			&& (noChooseErrorCheck(m_tabCurrent, rank - 1) == false)) {
			labelLeftSpinBox->setStatusError(bErrorStatus);
			lastLabelRightSpinBox->setStatusError(bErrorStatus);
			m_errType = 1;
			return;
		}
		
		if (rank + 1 != rangeTemp)
		{
			auto nextLabel = getTabTermSettingArea(m_tabCurrent)->m_vAreaLabels[rank + 1];
			if (nextLabel == nullptr) return;
			auto nextLabelLeftSpinBox = nextLabel->getLeftSpinBox();

			//参考老代码逻辑是：本级别右侧和下一级别左侧比较有问题，并且本级别未勾选情况，置本级别左侧与上一级别右侧出现的tip消失
			if ((labelRightSpinBox->getStatusError() == 1) && (nextLabelLeftSpinBox->getStatusError() == 1)
				&& (noChooseErrorCheck(m_tabCurrent, rank - 1) == true))
			{
				labelLeftSpinBox->setStatusError(0);
				lastLabelRightSpinBox->setStatusError(0);
				m_errType = 1;
				return;
			}
		}
	}
}

void MatrixTermSetting::resetTipShowStatus()
{
	int rank = -1;
	bool bLeft = false;
	auto labelArea = getTabTermSettingArea(m_tabCurrent);
	if (labelArea == nullptr) return;
	for (size_t i = 0; i < labelArea->m_vAreaLabels.size(); i++)
	{
		if (i == 10) break;
		auto label = labelArea->m_vAreaLabels[i];
		if (label->getLeftSpinBox()->getStatusError() || label->getRightSpinBox()->getStatusError())
		{
			rank = i;
			bLeft = (label->getLeftSpinBox()->getStatusError() == true) ? true : false;
			break;
		}
	}
	if (m_tipRank == rank) return;
	updateTipPos(rank,bLeft);
	m_tipRank = rank;
}

void MatrixTermSetting::updateTipPos(int rank,bool bleft)
{	
	QString strText;
	if (rank >= 0) {
		auto area = getTabTermSettingArea(m_tabCurrent);
		if (area == nullptr) return;
		auto label = area->m_vAreaLabels[rank];
		if (label == nullptr) return;
		auto spinBox = bleft == true ? label->getLeftSpinBox() : label->getRightSpinBox();
		
		QPoint p = spinBox->pos();
		int x = mapToGlobal(p).x();

		auto plabel = label->pos();
		int y = mapToGlobal(plabel).y();
		auto view = area->pos(); //当前TermSettingArea的位置
		int viewY = 0; 
		if (view.y() < 0)
		{
			viewY = -view.y(); // 往下拉取反
		}
		y = y - viewY;
		if (m_errType == 0)
		{
			strText = tr("请保证左边期限小于右边期限");
		}
		else if (m_errType == 1)
		{
			strText = tr("右侧期限不应大于下一级左侧期限");
		}
		QBTips::showText(QPoint(x,y),strText,this);
	}
}

void MatrixTermSetting::createLabelCheckedConnect()
{
	if (m_tabCurrent == BOND_GOV && !m_bGovBondLabelConnect) 
	{
		for (size_t  i = 0; i < m_bondGovLabelArea->m_vAreaLabels.size(); i++)
		{
			connect(m_bondGovLabelArea->m_vAreaLabels[i],&TermSettingLabel::stateChanged,this,&MatrixTermSetting::onCheckedBondLabel);
		}
		m_bGovBondLabelConnect = true;
	}
	else if (m_tabCurrent == BOND_CREDIT && !m_bCreditBondLabelConnect)
	{
		for (size_t  i = 0; i < m_bondCreditLabelArea->m_vAreaLabels.size(); i++)
		{
			connect(m_bondCreditLabelArea->m_vAreaLabels[i], &TermSettingLabel::stateChanged, this, &MatrixTermSetting::onCheckedBondLabel);
		}
		m_bCreditBondLabelConnect = true;
	}
	else if (m_tabCurrent == BOND_NCDTrade && !m_bNCDTradeBondLabelConnect)
	{
		for (size_t  i = 0; i < m_bondNCDLabelArea->m_vAreaLabels.size(); i++)
		{
			connect(m_bondNCDLabelArea->m_vAreaLabels[i], &TermSettingLabel::stateChanged, this, &MatrixTermSetting::onCheckedBondLabel);
		}
		m_bNCDTradeBondLabelConnect = true;
	}
}

void MatrixTermSetting::createLabelSpinBoxEditConnect()
{//connect传递给槽函数的是index
	if (m_tabCurrent == BOND_GOV && !m_bGovBondSpinBoxConnect)
	{
		for (size_t i = 0; i < m_bondGovLabelArea->m_vAreaLabels.size(); i++)
		{
			if (!m_bondGovLabelArea->m_vAreaLabels[i]->bhaveDobleSpinBox()) continue;
			connect(m_bondGovLabelArea->m_vAreaLabels[i]->getLeftSpinBox(), QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MatrixTermSetting::onEditedBondLabelSpinBox);
			connect(m_bondGovLabelArea->m_vAreaLabels[i]->getRightSpinBox(), QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MatrixTermSetting::onEditedBondLabelSpinBox);
		}
		m_bGovBondSpinBoxConnect = true;
	}
	else if (m_tabCurrent == BOND_CREDIT && !m_bCreditBondSpinBoxConnect)
	{
		for (size_t i = 0; i < m_bondCreditLabelArea->m_vAreaLabels.size(); i++)
		{
			connect(m_bondCreditLabelArea->m_vAreaLabels[i]->getLeftSpinBox(), QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MatrixTermSetting::onEditedBondLabelSpinBox);
			connect(m_bondCreditLabelArea->m_vAreaLabels[i]->getRightSpinBox(), QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MatrixTermSetting::onEditedBondLabelSpinBox);	
		}
		m_bCreditBondSpinBoxConnect = true;
	}
	else if (m_tabCurrent == BOND_NCDTrade && !m_bNCDTradeBondSpinBoxConnect)
	{
		for (size_t i = 0; i < m_bondNCDLabelArea->m_vAreaLabels.size(); i++)
		{
			connect(m_bondNCDLabelArea->m_vAreaLabels[i]->getLeftSpinBox(), QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MatrixTermSetting::onEditedBondLabelSpinBox);
			connect(m_bondNCDLabelArea->m_vAreaLabels[i]->getRightSpinBox(), QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &MatrixTermSetting::onEditedBondLabelSpinBox);
		}
		m_bNCDTradeBondSpinBoxConnect = true;
	}
}

bool MatrixTermSetting::noChooseErrorCheck(int RangeType, int RangeNo) const
{
	vector<UINT> vRangeData;
	getConfig(vRangeData, RangeType);

	if ((RangeNo >= 0) && (vRangeData[RangeNo] == 0))//需求确认如果本级不勾选，不判断下一级左侧数据与本级级右侧数据的大小
		return true;

	return false;
}

TermSettingArea* MatrixTermSetting::getTabTermSettingArea(int tabType) const
{
	if (tabType == BOND_GOV)
	{
		return m_bondGovLabelArea;
	}
	else if (tabType == BOND_CREDIT)
	{
		return m_bondCreditLabelArea;
	}
	else if (tabType == BOND_NCDTrade)
	{
		return m_bondNCDLabelArea;
	}
	return nullptr;
}

void MatrixTermSetting::initRangeInput()
{
	for (const auto& itRate : m_req->m_matrixTerm) {
		if (itRate.m_nRate != m_tabCurrent) continue; 
		int rank = 0;
		for (const auto &itRange : itRate.m_listTerm) {
			setRangeValue(rank,itRange.m_rangeLeft,itRange.m_rangeRight);
			++rank;
		}
	}
	changeRangeErrorStatus();
}

void MatrixTermSetting::setRangeValue(int rank,const char* leftValue,const char* rightValue)
{
	if (m_tabCurrent == eBondType::BOND_GOV)
	{
		m_bondGovLabelArea->m_vAreaLabels[rank]->setSpinBoxText(leftValue,rightValue);
	}
	else if (m_tabCurrent == eBondType::BOND_CREDIT)
	{
		m_bondCreditLabelArea->m_vAreaLabels[rank]->setSpinBoxText(leftValue, rightValue);
	}
	else if (m_tabCurrent == eBondType::BOND_NCDTrade)
	{
		m_bondNCDLabelArea->m_vAreaLabels[rank]->setSpinBoxText(leftValue, rightValue);
	}
}

void MatrixTermSetting::changeRangeErrorStatus()
{
	int rangeTemp;
	if ((m_tabCurrent == BOND_GOV) || (m_tabCurrent == BOND_CREDIT))
	{
		rangeTemp = 10;
	}
	else if (m_tabCurrent == BOND_NCDPrimary)
	{
		rangeTemp = 5;
	}
	else if (m_tabCurrent == BOND_NCDTrade)
	{
		rangeTemp = 7;
	}

	for (int i = 0; i < rangeTemp; i ++)
	{
		resetRangePairStatus(i);
	}
	resetTipShowStatus();
}

bool MatrixTermSetting::checkSaveReqValid()
{
	QString strTip;
	bool ret = checkSaveReqValid(strTip);
	if (!ret)
	{
		int nTipRank = m_tipRank;
		m_tipRank = -1;
		QMessageBox::information(this, "提示", strTip);
		if (nTipRank >= 0) {
			resetTipShowStatus();
		}
	}
	return ret;
}

bool MatrixTermSetting::checkSaveReqValid(QString& strTip)
{
	int ErrorType = 0;
	int iType = 0;
	CBondDealTermRange& range = CBondDealTermRange::instance();

	if (!m_req) return false;
	for (auto itMatrix : m_req->m_matrixTerm) {
		if (itMatrix.m_nRate == BOND_NCDPrimary) continue;
		bool bValid = true;
		int nLastDateLeft = 0, nLastDateRight = 0, RangeNo = 0;
		for (auto itRange : itMatrix.m_listTerm) {
			int nDateLeft, nDateRight;
			if (strcmp(itRange.m_term, "LangTerm") == 0) break; //超长

			nDateLeft = range.CalcDays(itRange.m_rangeLeft);
			nDateRight = range.CalcDays(itRange.m_rangeRight);
			if (nDateLeft >= nDateRight) {
				bValid = false;
				ErrorType = 0;
				break;
			}
			if ((nDateLeft < nLastDateRight) && (noChooseErrorCheck(itMatrix.m_nRate, RangeNo - 1) == false))  //判别会不会崩溃
			{
				bValid = false;
				ErrorType = 1;
				break;
			}
			nLastDateLeft = range.CalcDays(itRange.m_rangeLeft);
			nLastDateRight = range.CalcDays(itRange.m_rangeRight);
			RangeNo++;
		}
		if (!bValid) {
			if (!strTip.isEmpty()) { strTip += "\n"; }
			if (itMatrix.m_nRate == 3) iType = 13 + itMatrix.m_nRate;
			else iType = 1 + itMatrix.m_nRate;
		
			if (ErrorType == 0) strTip += NewStringTable::strBDMatrixerm(iType) + ": " + NewStringTable::strBDMatrixerm(6);
			if (ErrorType == 1) strTip += NewStringTable::strBDMatrixerm(iType) + ": " + NewStringTable::strBDMatrixerm(17);
		}
	}
	if (!strTip.isEmpty()) return false;
	return true;
}

void MatrixTermSetting::onChangeBondTab(int index)
{
	if (!m_bondGovLabelArea || !m_bondCreditLabelArea || !m_bondNCDLabelArea) return;
	
	saveRangeInfo();

	if (index == 2)  m_tabCurrent = index + 1; //NCD二级成交
	else m_tabCurrent = index;

	m_bondGovLabelArea->hide();
	m_bondGovScrollArea->hide();
	m_bondCreditLabelArea->hide();
	m_bondCreditScrollArea->hide();
	m_bondNCDLabelArea->hide();
	m_bondNCDScrollArea->hide();

	if (index == BOND_GOV)
	{
		m_bondGovLabelArea->show();
		m_bondGovScrollArea->show();
	}
	else if (index == BOND_CREDIT)
	{
		m_bondCreditLabelArea->show();
		m_bondCreditScrollArea->show();
	}
	else 
	{
		m_bondNCDLabelArea->show();
		m_bondNCDScrollArea->show();
	}
	initRangeInput();		//spinbox输入值
	changeTermRangeText();  //select
	createLabelCheckedConnect();
	createLabelSpinBoxEditConnect();
}

void MatrixTermSetting::onCheckedBondLabel(int index)
{
	int iRangeNum = 0;
	vector<UINT> vRangeData;
	getConfig(vRangeData, m_tabCurrent);

	for (int i = 0; i <= ID_CHK_LONGTERM - ID_CHK_1Y; i++) {
		if (m_tabCurrent == BOND_GOV)
		{
			m_IntData[i] = vRangeData[i];
		}
		else if ((m_tabCurrent == BOND_CREDIT) && (i < 10))
		{
			m_CretData[i] = vRangeData[i];
		}
		else if ((m_tabCurrent == BOND_NCDTrade) && (i < 7))
		{
			m_NCDData[i] = vRangeData[i];
		}
	}

	for (int i = 0; i <= ID_CHK_LONGTERM - ID_CHK_1Y; i++) {
		if (index == i)
		{
			if (m_tabCurrent == BOND_GOV)
			{
				m_IntData[i] = m_bondGovLabelArea->m_vAreaLabels[i]->isSelected();
			}
			else if ((m_tabCurrent == BOND_CREDIT) && (i < 10))
			{
				m_CretData[i] = m_bondCreditLabelArea->m_vAreaLabels[i]->isSelected();
			}
			else if (((m_tabCurrent == BOND_NCDTrade)) && (i < 7))
			{
				m_NCDData[i] = m_bondNCDLabelArea->m_vAreaLabels[i]->isSelected();
			}
		}

		if (((m_tabCurrent == BOND_CREDIT)&& (i < 10) && (m_CretData[i] == 1)) || ((m_tabCurrent == BOND_GOV) && (m_IntData[i] == 1)))
		{
			iRangeNum++;
		}

		if ((m_tabCurrent == BOND_NCDTrade) && (m_NCDData[i] == 1) && (i < 7))
		{
			iRangeNum++;
		}
	}

	////利率债不能选中少于7个，其余类型不能选中少于6个
	if (((m_tabCurrent == BOND_GOV) && (iRangeNum < 7)) || ((m_tabCurrent != BOND_GOV) && (iRangeNum < 6)))
	{
		//标志置回
		for (int i = 0; i <= ID_CHK_LONGTERM - ID_CHK_1Y; i++) {
			if (index == i)
			{
				if (m_tabCurrent == BOND_GOV)
				{
					m_IntData[i] = 1;
					m_bondGovLabelArea->m_vAreaLabels[i]->setSelectState(Qt::Checked,false);
				}
				else if ((m_tabCurrent == BOND_CREDIT) && (i < 10))
				{
					m_CretData[i] = 1;
					m_bondCreditLabelArea->m_vAreaLabels[i]->setSelectState(Qt::Checked, false);
				}
				else if (((m_tabCurrent == BOND_NCDTrade)) && (i < 7))
				{
					m_NCDData[i] = 1;
					m_bondNCDLabelArea->m_vAreaLabels[i]->setSelectState(Qt::Checked, false);
				}
			}
		}
		if (m_tabCurrent != BOND_GOV)	  QMessageBox::information(this, "提示", tr("所选期限不应少于6个"));
		else if (m_tabCurrent == BOND_GOV) QMessageBox::information(this, "提示", tr("所选期限不应少于7个")); 

	}

	saveConfig();
	emit notifyTermChanged(m_tabCurrent);
	changeRangeErrorStatus();
}

void MatrixTermSetting::onEditedBondLabelSpinBox()
{
	const DoubleSpinBox* spBox = qobject_cast<DoubleSpinBox*>(QObject::sender());
	int index = spBox->m_index;
	resetRangePairStatus(index);
	resetTipShowStatus();
}

//涨跌bp
MatrixUpDownBp::MatrixUpDownBp(QWidget* p, int bondType, xQBBondDealTermRgReq* req)
	:QWidget(p),m_req(req)
{
	auto vLayout = new QVBoxLayout(this);
	vLayout->setContentsMargins(0, 7, 0, 0);
	m_tabType = new STabCtrl(this);
	m_tabType->addTab(NewStringTable::strBDMatrixerm(1));
	m_tabType->addTab(NewStringTable::strBDMatrixerm(2));
	m_tabType->addTab(NewStringTable::strBDMatrixerm(16));
	m_tabType->setFixedSize(384, 22);
	vLayout->addWidget(m_tabType);
	vLayout->addSpacing(14);

	//利率债
	m_bondGOVUpDownArea = new upDownBpArea(this);
	m_bondGOVUpDownArea->setMinimumHeight(56);
	vLayout->addWidget(m_bondGOVUpDownArea);
	m_bondGOVUpDownArea->hide();
	
	//信用债
	m_bondCreditUpDownArea = new upDownBpArea(this);
	m_bondCreditUpDownArea->setMinimumHeight(56);
	vLayout->addWidget(m_bondCreditUpDownArea);
	m_bondCreditUpDownArea->hide();

	//NCD二级成交
	m_bondNCDUpDownArea = new upDownBpArea(this);
	m_bondNCDUpDownArea->setMinimumHeight(56);
	vLayout->addWidget(m_bondNCDUpDownArea);
	m_bondNCDUpDownArea->hide();
	vLayout->addStretch(-1);
	setTabType(bondType);
	connect(m_tabType, &STabCtrl::tabSelected, this, &MatrixUpDownBp::onChangeBondTab);
}

upDownBpArea* MatrixUpDownBp::getCurrentTypeArea(int type) const
{
	if (type == BOND_GOV)
	{
		return m_bondGOVUpDownArea;
	}
	else if (type == BOND_CREDIT)
	{
		return m_bondCreditUpDownArea;
	}
	else if (type == BOND_NCDTrade)
	{
		return m_bondNCDUpDownArea;
	}
	return nullptr;
}

void MatrixUpDownBp::setTabType(int index)
{
	m_tabType->selectTab(index == 3 ? index - 1 : index);
	m_tabCurrent = index;
	setSCheckExType();
	onChangeBondTab(index);
}

void MatrixUpDownBp::createSCheckExConnect()
{
	if (m_tabCurrent == BOND_GOV && !m_bGovSCheckedConnect)
	{
		connect(m_bondGOVUpDownArea->getSRadioGroup()->getSCheckEx(eType_PreClose), &SCheckEx::stateChanged, this, &MatrixUpDownBp::onRatioClick);
		connect(m_bondGOVUpDownArea->getSRadioGroup()->getSCheckEx(eType_CDC), &SCheckEx::stateChanged, this, &MatrixUpDownBp::onRatioClick);
		m_bGovSCheckedConnect = true;
	}
	else if (m_tabCurrent == BOND_CREDIT && !m_bCreditSCheckedConnect)
	{
		connect(m_bondCreditUpDownArea->getSRadioGroup()->getSCheckEx(eType_PreClose), &SCheckEx::stateChanged, this, &MatrixUpDownBp::onRatioClick);
		connect(m_bondCreditUpDownArea->getSRadioGroup()->getSCheckEx(eType_CDC), &SCheckEx::stateChanged, this, &MatrixUpDownBp::onRatioClick);
		m_bCreditSCheckedConnect = true;
	}
	else if (m_tabCurrent == BOND_NCDTrade && !m_bNCDTradeSCheckedConnect)
	{
		connect(m_bondNCDUpDownArea->getSRadioGroup()->getSCheckEx(eType_PreClose), &SCheckEx::stateChanged, this, &MatrixUpDownBp::onRatioClick);
		connect(m_bondNCDUpDownArea->getSRadioGroup()->getSCheckEx(eType_CDC), &SCheckEx::stateChanged, this, &MatrixUpDownBp::onRatioClick);
		m_bNCDTradeSCheckedConnect = true;
	}
}

void MatrixUpDownBp::setSCheckExType()
{
	bool found = false;
	for (auto it : m_req->m_matrixTerm)
	{
		if (it.m_nRate == m_tabCurrent)
		{
			auto SRadioGroup = getCurrentTypeArea(m_tabCurrent)->getSRadioGroup();
			if (SRadioGroup == nullptr) return;
			auto preCloseCheck = SRadioGroup->getSCheckEx(eType_PreClose);
			auto CDCCheck = SRadioGroup->getSCheckEx(eType_CDC);
			if (preCloseCheck == nullptr || CDCCheck == nullptr) return;
			if (it.m_diffType == 0)
			{
				preCloseCheck->setSelectState(Qt::Checked);
				CDCCheck->setSelectState(Qt::Unchecked);
				found = true;
			}
			else if (it.m_diffType == 1)
			{
				preCloseCheck->setSelectState(Qt::Unchecked);
				CDCCheck->setSelectState(Qt::Checked);
				found = true;
			}
			else
			{
				switch (m_tabCurrent)
				{
				case eBondType::BOND_GOV:
					preCloseCheck->setSelectState(Qt::Checked);
					CDCCheck->setSelectState(Qt::Unchecked);
					it.m_diffType = 0;
					break;
				case eBondType::BOND_CREDIT:
				case eBondType::BOND_NCDPrimary:
				case eBondType::BOND_NCDTrade:
					preCloseCheck->setSelectState(Qt::Unchecked);
					CDCCheck->setSelectState(Qt::Checked);
					it.m_diffType = 1;
					break;
				}
			}
			break;
		}
	}
}

void MatrixUpDownBp::onChangeBondTab(int index)
{
	if (!m_bondGOVUpDownArea || !m_bondCreditUpDownArea || !m_bondNCDUpDownArea) return;

	if (index == 2)  m_tabCurrent = index + 1; //NCD二级成交
	else m_tabCurrent = index;

	m_bondGOVUpDownArea->hide();
	m_bondCreditUpDownArea->hide();
	m_bondNCDUpDownArea->hide();
	
	if (index == BOND_GOV)
	{
		m_bondGOVUpDownArea->show();
	}
	else if (index == BOND_CREDIT)
	{
		m_bondCreditUpDownArea->show();
	}
	else
	{
		m_bondNCDUpDownArea->show();
	}
	setSCheckExType();
	createSCheckExConnect();
}

void MatrixUpDownBp::onRatioClick(int index)
{
	int id = (int)index;
	int nType = -1;
	auto SRadioGroup = getCurrentTypeArea(m_tabCurrent)->getSRadioGroup();
	auto preCloseSCheck = SRadioGroup->getSCheckEx(eType_PreClose);
	auto CDCSCheck = SRadioGroup->getSCheckEx(eType_CDC);

	switch (id)
	{
	case eType_PreClose:
		CDCSCheck->setSelectState(Qt::Unchecked);
		nType = eType_PreClose;
		break;
	case eType_CDC:
		preCloseSCheck->setSelectState(Qt::Unchecked);
		nType = eType_CDC;
		break;
	default:
		break;
	}
	for (auto& it : m_req->m_matrixTerm)
	{
		if (it.m_nRate == m_tabCurrent)
		{
			it.m_diffType = nType;
			break;
		}
	}
}

upDownBpArea::upDownBpArea(QWidget* p)
	:QWidget(p)
{
	auto vLayout = new QVBoxLayout(this);
	vLayout->setContentsMargins(0, 0, 0, 0);
	m_preClose = new SCheckEx(tr("按昨收涨跌"), this);
	m_preClose->setSelectType(SCheckEx::SelectType::Radio);
	m_preClose->setFixedSize(374, 27);
	m_preClose->setIndex(0);
	vLayout->addWidget(m_preClose);

	vLayout->addSpacing(3);
	m_CDC = new SCheckEx(tr("按中债偏离"), this);
	m_CDC->setSelectType(SCheckEx::SelectType::Radio);
	m_CDC->setFixedSize(374, 27);
	m_CDC->setIndex(1);
	vLayout->addWidget(m_CDC);

	m_rg = new SRadioGroup(this);
	m_rg->addRadio(m_preClose);
	m_rg->addRadio(m_CDC);
}

//数据显示
MatrixDataDisplaySetting::MatrixDataDisplaySetting(QWidget* p, xQBBondDealTermRgReq* req)
	:QWidget(p),m_req(req)
{
	auto vLayout = new QVBoxLayout(this);
	vLayout->setContentsMargins(0, 20, 8, 0);

	QLabel* txtDisplay = new QLabel(tr("文字展示"), this);
	txtDisplay->setStyleSheet(QString("font:12px;color:#%1;font-weight:bold;").arg(NAME_COLOR("SupportingWord").rgb(), 0, 16));
	vLayout->addWidget(txtDisplay, Qt::AlignLeft);
	vLayout->addSpacing(12);

	auto txtDisplayHLayout = new QHBoxLayout();
	txtDisplayHLayout->setContentsMargins(0, 0, 0, 0);

	m_yield = new SCheckEx(tr("收益率"), this);
	m_yield->setFixedSize(185, 25);
	m_yield->setSelectType(SCheckEx::SelectType::Radio);
	m_yield->setIndex(0);
	txtDisplayHLayout->addWidget(m_yield);
	txtDisplayHLayout->addSpacing(4);

	m_bps = new SCheckEx(tr("bps"), this);
	m_bps->setFixedSize(185, 25);
	m_bps->setSelectType(SCheckEx::SelectType::Radio);
	m_bps->setIndex(1);
	txtDisplayHLayout->addWidget(m_bps);
	vLayout->addLayout(txtDisplayHLayout);
	vLayout->addSpacing(10);

	m_textShowRGroup = new SRadioGroup(this);
	m_textShowRGroup->addRadio(m_yield);
	m_textShowRGroup->addRadio(m_bps);

	QLabel* chartDisplay = new QLabel(tr("图形展示"), this);
	chartDisplay->setStyleSheet(QString("font:12px;color:#%1;font-weight:bold;").arg(NAME_COLOR("SupportingWord").rgb(), 0, 16));
	vLayout->addWidget(chartDisplay, Qt::AlignLeft);

	vLayout->addSpacing(3);

	m_heatMap = new SCheckEx(tr("热力图"), this);
	m_heatMap->setFixedSize(374, 25);
	m_heatMap->setSelectType(SCheckEx::SelectType::Radio);
	m_heatMap->setIndex(2);
	vLayout->addWidget(m_heatMap);
	vLayout->addSpacing(3);

	m_horizontalBarChart = new SCheckEx(tr("横向柱状图"), this);
	m_horizontalBarChart->setFixedSize(374, 25);
	m_horizontalBarChart->setSelectType(SCheckEx::SelectType::Radio);
	m_horizontalBarChart->setIndex(3);
	vLayout->addWidget(m_horizontalBarChart);
	vLayout->addSpacing(3);

	m_verticalBarChart = new SCheckEx(tr("纵向柱状图"), this);
	m_verticalBarChart->setFixedSize(374, 25);
	m_verticalBarChart->setSelectType(SCheckEx::SelectType::Radio);
	m_verticalBarChart->setIndex(4);
	vLayout->addWidget(m_verticalBarChart);

	m_chartShowRGroup = new SRadioGroup(this);
	m_chartShowRGroup->addRadio(m_heatMap);
	m_chartShowRGroup->addRadio(m_horizontalBarChart);
	m_chartShowRGroup->addRadio(m_verticalBarChart);

	vLayout->addStretch(-1);
	setCurrentType();
	connect(m_yield,&SCheckEx::stateChanged,this,&MatrixDataDisplaySetting::onRatioClick);
	connect(m_bps,&SCheckEx::stateChanged,this,&MatrixDataDisplaySetting::onRatioClick);
	connect(m_heatMap,&SCheckEx::stateChanged,this,&MatrixDataDisplaySetting::onRatioClick);
	connect(m_horizontalBarChart,&SCheckEx::stateChanged,this,&MatrixDataDisplaySetting::onRatioClick);
	connect(m_verticalBarChart,&SCheckEx::stateChanged,this,&MatrixDataDisplaySetting::onRatioClick);
}

void MatrixDataDisplaySetting::setCurrentType()
{
	int textShowGroupSize = m_textShowRGroup->getSCheckExCount();
	for (int i = 0; i < textShowGroupSize; ++i)
	{
		auto SCheckExText = m_textShowRGroup->getSCheckEx(i);
		if (SCheckExText == nullptr) return;
		SCheckExText->setSelectState(i == m_req->m_TextShowType ? Qt::Checked : Qt::Unchecked);
	}
	//index是连着的
	int chartShowGroupSize = m_chartShowRGroup->getSCheckExCount();
	for (int i = textShowGroupSize; i < (textShowGroupSize + chartShowGroupSize); ++i)
	{
		auto SCheckExChart = m_chartShowRGroup->getSCheckEx(i);
		if (i < textShowGroupSize || SCheckExChart == nullptr) return;
		SCheckExChart->setSelectState((i - textShowGroupSize) == m_req->m_ChartShowType ? Qt::Checked : Qt::Unchecked);
	}
}

void MatrixDataDisplaySetting::initSCheckEx(int index)
{
	switch (index)
	{
		case eType_Ytm:
			m_textShowRGroup->getSCheckEx(eType_bps)->setSelectState(Qt::Unchecked);
			break;
		case eType_bps:
			m_textShowRGroup->getSCheckEx(eType_Ytm)->setSelectState(Qt::Unchecked);
			break;
		case eType_HeatMap:
			m_chartShowRGroup->getSCheckEx(eType_HorizontalBarChart)->setSelectState(Qt::Unchecked);
			m_chartShowRGroup->getSCheckEx(eType_VerticalBarChart)->setSelectState(Qt::Unchecked);
			break;
		case eType_HorizontalBarChart:
			m_chartShowRGroup->getSCheckEx(eType_HeatMap)->setSelectState(Qt::Unchecked);
			m_chartShowRGroup->getSCheckEx(eType_VerticalBarChart)->setSelectState(Qt::Unchecked);
			break;
		case eType_VerticalBarChart:
			m_chartShowRGroup->getSCheckEx(eType_HorizontalBarChart)->setSelectState(Qt::Unchecked);
			m_chartShowRGroup->getSCheckEx(eType_HeatMap)->setSelectState(Qt::Unchecked);
			break;
		default:
			break;
	}
}

void MatrixDataDisplaySetting::onRatioClick(int index)
{
	initSCheckEx(index);
	if (!m_req)		return;
	switch (index)
	{
		case eType_Ytm:
			m_req->m_TextShowType = 0;
			break;
		case eType_bps:
			m_req->m_TextShowType = 1;
			break;
		case eType_HeatMap:
			m_req->m_ChartShowType = 0;
			break;
		case eType_HorizontalBarChart:
			m_req->m_ChartShowType = 1;
			break;
		case eType_VerticalBarChart:
			m_req->m_ChartShowType = 2;
			break;
		default:
			break;
	}
}

//Matrix设置
BondDealMatrixSettingDlg::BondDealMatrixSettingDlg(QWidget* parent, int bondType, xQBBondDealTermRgReq* req,int nParentMode)
	:SPopupWindow(parent),m_bondType(bondType),m_req(req),m_nParentMode(nParentMode)
{
	setFixedSize(518, 414);
	setTitle(NewStringTable::strBDMatrixerm(0));

	QVBoxLayout* mainLayout = contentLayout();

	auto hLayout = new QHBoxLayout();
	hLayout->setContentsMargins(0, 0, 0, 0);
	mainLayout->addLayout(hLayout);
	mainLayout->setSpacing(0);

	m_leftList = new QListWidget();
	hLayout->addWidget(m_leftList,Qt::AlignLeft);

	m_leftList->setStyleSheet(QString(
		"QListWidget				{background-color:#%2;border:0px;}"
		"QListWidget::Item			{color:#%1; border:0px; background-color:#%2; text-align:left;padding-left:3px;height:40px;width:90px;}"
		"QListWidget::Item:hover	{color:#%1; border:0px; background-color:#%3; text-align:left;padding-left:3px;}"
		"QListWidget::Item:selected {color:#%4; border:0px; background-color:#%5; border-color:#%5;text-align:left;padding-left:3px;}")
		.arg(NAME_COLOR("TextNormal").rgb(), 0, 16)
		.arg(NAME_COLOR("BasicPlate").rgb(), 0, 16)
		.arg(NAME_COLOR("Hover").rgb(), 0, 16)
		.arg(NAME_COLOR("Highlight").rgb(), 0, 16)
		.arg(NAME_COLOR("PartPlate").rgb(), 0, 16));
	m_leftList->setMinimumHeight(120);
	m_leftList->setMaximumWidth(93);
	m_leftList->setFocusPolicy(Qt::NoFocus);

	for (int i = 0; i < ItemNum; i++)
	{
		auto item = new QListWidgetItem;
		item->setText(NewStringTable::strMatrixSettingDiff(i));
		if (i == 0)
			item->setSelected(true);
		item->setSizeHint({ 90,40 });
		m_leftList->insertItem(i, item);
	}
	m_leftList->item(0)->setSelected(true);
	connect(m_leftList, &QListWidget::itemPressed, this, &BondDealMatrixSettingDlg::onListClick);
	hLayout->addSpacing(15);

	//默认是期限设置页面
	m_termSetting = new MatrixTermSetting(this, m_bondType, req);
	m_termSetting->setFixedSize(384, 350);
	hLayout->addWidget(m_termSetting);

	m_upDownBp = new MatrixUpDownBp(this, m_bondType,req);
	m_upDownBp->setFixedSize(384, 180);
	hLayout->addWidget(m_upDownBp);
	m_upDownBp->hide();

	m_dataDisplaySetting = new MatrixDataDisplaySetting(this,req);
	m_dataDisplaySetting->setFixedSize(384,210);
	hLayout->addWidget(m_dataDisplaySetting);
	m_dataDisplaySetting->hide();

	auto btn = addBtn(QMessageBox::Ok, tr("确定"));
	connect(btn, &QPushButton::pressed, this, &BondDealMatrixSettingDlg::onApplyChange);
	btn = addBtn(QMessageBox::Cancel, tr("取消"));
	connect(btn, &QPushButton::pressed, this, QOverload<>::of(&QDialog::reject));
	connect(m_termSetting, &MatrixTermSetting::notifyTermChanged, this, &BondDealMatrixSettingDlg::onNotifyTermChange);
}

void BondDealMatrixSettingDlg::paintEvent(QPaintEvent* event)
{
	SPopupWindow::paintEvent(event);
	QStylePainter painter(this);

	QLineF line(112, 10,112,350);
	painter.setPen(StyleMgr::instance().color("BorderNormal"));
	painter.drawLine(line);
}

void BondDealMatrixSettingDlg::changePage(int index)
{
	if (!m_termSetting || !m_upDownBp || !m_dataDisplaySetting) return;
	m_termSetting->hide();
	m_upDownBp->hide();
	m_dataDisplaySetting->hide();

	if (index == TermSetting)
	{
		m_termSetting->show();
	}
	else if (index == UpDownBp)
	{
		m_upDownBp->show();
	}
	else if (index == DataDisplaySetting)
	{
		m_dataDisplaySetting->show();
	}
}

void BondDealMatrixSettingDlg::changeReqParam()
{
	xQBBondDealTermRgReq req;
	for (auto itRate : m_req->m_matrixTerm) {
		sBondDealTermList unitMatrix;
		unitMatrix.m_nRate = itRate.m_nRate;
		for (auto &itRange : itRate.m_listTerm) {
			sBondDealTermRgUnit unitTerm;
			FIELDCOPY(unitTerm.m_term, itRange.m_term);
			if (CBondDealTermRange::instance().GetRange(unitTerm, static_cast<CBondDealTermRange::emBondType>(unitMatrix.m_nRate))) {
				if (strcmp(unitTerm.m_rangeLeft, itRange.m_rangeLeft) != 0 || strcmp(unitTerm.m_rangeRight, itRange.m_rangeRight) != 0) {
					unitMatrix.m_listTerm.push_back(itRange);
				}
			}
		}
		unitMatrix.m_diffType = itRate.m_diffType;
		int nDiff = CBondDealTermRange::instance().GetDiffType(static_cast<CBondDealTermRange::emBondType>(unitMatrix.m_nRate));
		if (unitMatrix.m_diffType == nDiff && unitMatrix.m_listTerm.empty())continue;
		req.m_matrixTerm.push_back(unitMatrix);
	}
	m_req->m_matrixTerm = req.m_matrixTerm;
	saveConfig(m_req->m_TextShowType, m_req->m_ChartShowType);
}

void BondDealMatrixSettingDlg::saveConfig(int textShowType, int chartShowType)
{
	QSettings settings(FileSys::instance()->writeableAppCfgDir() + "/gszhConfig.ini", QSettings::IniFormat);

	settings.beginGroup("matrix");
	settings.setValue("text", textShowType);
	settings.setValue("chart", chartShowType);
	settings.endGroup();
}

void BondDealMatrixSettingDlg::onListClick(QListWidgetItem* item)
{
	for (int i = 0; i < m_leftList->count(); i++)
	{
		if (m_leftList->item(i)->isSelected())
		{
			changePage(i);
			break;
		}
	}
}

void BondDealMatrixSettingDlg::onApplyChange()
{
	if (!m_termSetting->checkSaveReqValid()) {
		return;
	}
	m_termSetting->saveRangeInfo();
	changeReqParam();
	SPopupWindow::accept();
}

void BondDealMatrixSettingDlg::onNotifyTermChange(int type)
{
	m_req->m_bChangeTermRange = true;
	type += 1;
	emit notifyMatrixTermChanged(type);
}
